package handler

import (
	"common/biz"
	"common/resp"
	"context"
	"core/remote"
	"core/service"
	"encoding/json"
	"game/logic"
	"game/models"
)

type UnionHandler struct {
	userService *service.UserService
	um          *logic.UnionManager
}

// CreateRoom 创建房间
func (h *UnionHandler) CreateRoom(session *remote.Session, msg []byte) any {
	uid := session.Msg.Uid
	if len(uid) == 0 {
		return resp.F(biz.InvalidUsers)
	}
	// 1. 接收参数
	param := new(models.CreateRoomRequest)
	if err := json.Unmarshal(msg, param); err != nil {
		return resp.F(biz.RequestDataError)
	}
	// 2.根据用户 id 查询用户信息
	user, err := h.userService.FindUserByUid(context.TODO(), uid)
	if err != nil {
		return resp.F(biz.SqlError)
	}
	if user == nil {
		return resp.F(biz.InvalidUsers)
	} // 3. 创建房间
	union := h.um.GetOrAdd(param.UnionId)
	if err := union.CreateRoom(session, param, user); err != nil {
		return resp.F(err)
	}
	return resp.S(nil)
}

// JoinRoom 加入房间
func (h *UnionHandler) JoinRoom(session *remote.Session, msg []byte) any {
	uid := session.Msg.Uid
	if len(uid) == 0 {
		return resp.F(biz.InvalidUsers)
	}
	// 1. 接收参数
	param := new(models.JoinRoomRequest)
	if err := json.Unmarshal(msg, param); err != nil {
		return resp.F(biz.RequestDataError)
	}
	// 2.根据用户 id 查询用户信息
	user, err := h.userService.FindUserByUid(context.TODO(), uid)
	if err != nil {
		return resp.F(biz.SqlError)
	}
	if bizErr := h.um.JoinRoom(session, param.RoomID, user); bizErr != nil {
		return resp.F(bizErr)
	}
	return resp.S(nil)
}

func NewUnionHandler(userService *service.UserService, um *logic.UnionManager) *UnionHandler {
	return &UnionHandler{
		userService: userService,
		um:          um,
	}
}
